<template>
  <div class="curve" style="">
  	<!--  图表  -->
    <div class="curve--chart__wrap" ref="chartWrap" style="height: 100px;" id="chart__wrap">
        <div id="myChart" :style="{width:chartWidth, height:chartHeight}"></div>  
    </div>
    
    <!-- 日周月切换 -->
    <div class="footer" style="height: 49px;border-top: 1px solid rgb(213,217,220);background: #efefef;line-height:50px;">
       <div v-bind:style="{ width: dateWidth }" style="height:100%;margin:0 auto;display:flex;justify-content: space-around;align-items: center;"> 
        <div 
          @click="toggleDate(1)" 
          :class="[{'active': activeDate === 'dayActive'},'footer__day', 'date']">日</div>
        <div 
          @click="toggleDate(7)" 
          :class="[{'active': activeDate === 'weekActive'},'footer__week', 'date']">周</div>
        <div 
          @click="toggleDate(30)"
          :class="[{'active': activeDate === 'monthActive'}, 'footer__moonth', 'date']">月</div>
       </div> 
    </div>
    
    <!-- 温湿度文字竖屏显示 -->
    <div class="header" style="position: absolute;top: 0;" v-if="headerLeftShow">
    	<div>
    		<div class="header__left">
		        <p>
		          	当前温度
		          <span class="current-temprature-value__left">{{ renderTemp }}</span>
              <span class="current-tetemprature-unit__left">{{tempType ? 'F' : '℃'}}</span>
		        </p>
		        <p style="">
		          	当前湿度
		          <span class="current-temprature-value__left">{{ renderHum }}</span>
              <span class="current-tetemprature-unit__left">%</span>
		        </p>
      		</div>
    	</div>
    </div>

    <!-- 温湿度横屏显示 -->
    <div style="position: absolute;top: 0;padding: 30px 0px 0px 16px;" v-if="!headerLeftShow">
    	<div>   		
    	  <div style="">
	        <p>当前温度 {{renderTemp}} {{tempType ? 'F' : '℃'}}   当前湿度 {{renderHum}}%</p>
	      </div>
    	</div>  
    </div>
    
    <!-- 上下层切换  -->
    <div v-if="initFinish" class="header__content" :style="{ width:headerContent }" style="position: absolute; top: 0; margin: auto; left: 0; right: 0; padding-top: 24px;z-index:99999;" >
        <div class="floor__wrap">
          <div 
            @click="toggleFloor(0)" 
            :class="['top-floor', {'active': topFloorActive}]">
            上层
          </div>
          <div
            @click="toggleFloor(1)" 
            :class="['bottom-floor', {'active': !topFloorActive}]">
            下层
          </div>
        </div>
    </div>
    
  </div>
</template>
<script>
import _ from 'lodash'
import api from '@/api'
import { mapGetters } from 'vuex'
import { CIGARTYPE } from '../cigar-device-controller/CIGARTYPE'
import formatDate from '@/utils/formatDate.js'
let echarts = require('echarts/lib/echarts')
require('echarts/lib/chart/line')
require('echarts/lib/component/tooltip')
require('echarts/lib/component/legend')
export default {
  name: 'CigarCurve',
  data () {
    return {
      total: 0,
      snapshots: [],
      chartWidth: '',
      chartHeight: '',
      myChart: null,

      topFloorActive: true,
      activeDate: 'dayActive',
      date: 1,
      headerContent: '',
      dateWidth: '',
      headerLeftShow: true,
      xAxisData: [],

      selectedRule: {},
      allDatapoints: [],
      initFinish: false,
      firstInit: true,
      editing: true,
      tempType: 0,
      tempAndHum: [
        {
          name: '上区显示温度',
          title: 'Up_Display_Tempurature',
          key: CIGARTYPE.Up_Display_Tempurature,
          value: 0
        },
        {
          name: '上区显示湿度',
          title: 'Up_Display_Humidity',
          key: CIGARTYPE.Up_Display_Humidity,
          value: 0
        },
        {
          name: '下区显示温度',
          title: 'Down_Set_Tempurature',
          key: CIGARTYPE.Down_Display_Tempurature,
          value: 0
        },
        {
          name: '下区显示湿度',
          title: 'Down_Set_Humidity',
          key: CIGARTYPE.Down_Display_Humidity,
          value: 0
        }
      ]
      // bottom: '50px'
    }
  },
  watch: {
    date (newVal) {
      this.init()
    },
    topFloorActive (newval) {
      this.init()
    },
    socketList (newVal) {
      if (newVal) {
        this.linkSocket()
      }
    },
    getNameDevicesList (newVal) {
      if (newVal) {
        this.storage()
      }
    }
  },
  computed: {
    series () {
      let result = []
      // 上层温湿度对应的数据端点为3,5 下层对应的为7,9 后期调整数据结构
      let dp = this.topFloorActive ? [3, 5] : [7, 9]
      let selectedDatapoints = _.filter(this.allDatapoints, (item) => {
        return item.index === dp[0] || item.index === dp[1]
      })
      let usefulDp = _.filter(selectedDatapoints, (item) => {
        return this.canBeCounted(item.type)
      })
      if (!usefulDp || !usefulDp.length) {
        return result
      }
      usefulDp.forEach((item) => {
        result.push({
          name: `${item.name}`,
          type: 'line',
          data: [],
          dpIndex: item.index
        })
      })
      this.xAxisData = []
      let tempData = _.clone(this.snapshots)
      let filterTempData = _.groupBy(tempData, (item) => {
        let date = +new Date(item.snapshot_date) + 1000 * 3600
        return formatDate(date, 'MM-dd hh' + ':00', true)
      })
      let filterTempDataArr = []
      for (let ts in filterTempData) {
        filterTempData[ts].sort((a, b) => {
          a = +new Date(a.snapshot_date)
          b = +new Date(b.snapshot_date)
          return a - b
        })
        let value = filterTempData[ts].slice(-1)
        if (value.length) {
          value = value[0]
        }
        filterTempDataArr.push({
          date: ts,
          value: value
        })
      }
      let sortTempDataArr = _.sortBy(filterTempDataArr, (item) => {
        return +new Date(item.date)
      })
      // TODO filterTempDataArr为[{8-18 13:00}, {8-17 13:00}] 临时调用filterTempDataArr的结构截取,
      // 选取天的时候结构为13:00 选取周或者月份为8-17
      sortTempDataArr.forEach((item) => {
        this.xAxisData.push(item.date)
        result.forEach((r) => {
          r.data.push(item.value[r.dpIndex])
        })
      })
      return {
        temArry: result[0].data,
        humArry: result[1].data
      }
    },
    // 设备列表
    ...mapGetters({
      socketList: 'control/socketList',
      getNameDevicesList: 'control/cigarDeviceList'
    }),

    // 渲染温度
    renderTemp () {
      return this.topFloorActive ? this.tempAndHum[0].value : this.tempAndHum[2].value
    },
    // 渲染湿度
    renderHum () {
      return this.topFloorActive ? this.tempAndHum[1].value : this.tempAndHum[3].value
    }
  },
  mounted () {
    this.$Title.set('温湿度曲线')
    this.myChart = echarts.init(document.getElementById('myChart'))
    if (window.orientation === 180 || window.orientation === 0) {
      window.clearTimeout(this.onorientationchangeId)
      this.onorientationchangeId = setTimeout(() => {
        this.headerContent = '42.8%'
        this.initFinish = true
        this.dateWidth = '84%'
        this.headerLeftShow = true
      }, 500)
    }
    if (window.orientation === 90 || window.orientation === -90) {
      window.clearTimeout(this.onorientationchangeId)
      this.onorientationchangeId = setTimeout(() => {
        this.headerContent = '24.1%'
        this.initFinish = true
        this.dateWidth = '46%'
        this.headerLeftShow = false
      }, 500)
    }
    this.storage()
    this.$nextTick(async () => {
      this.init()
      this.linkSocket()
    })
  },
  methods: {
    // 切换上下层
    async init () {
      this.editing = true
      await this.fetchSnapshot()
      await this.fetchDatapoint()
      await this.changeOptions()
      await this.checkOrientation()
      this.editing = false
    },
    toggleFloor (isTopFloor) {
      if (!this.firstInit && this.editing) return
      if (isTopFloor === 0) {
        this.topFloorActive = true
      } else {
        this.topFloorActive = false
      }
      this.firstInit = false
    },
    // 切换时间范围
    toggleDate (period) {
      if (!this.firstInit && this.editing) return
      if (period === 30) {
        this.date = 30
        this.activeDate = 'monthActive'
      } else if (period === 7) {
        this.date = 7
        this.activeDate = 'weekActive'
      } else {
        this.date = 1
        this.activeDate = 'dayActive'
      }
      this.firstInit = false
    },
    getParams (number) {
      let year = new Date().getFullYear()
      let month = new Date().getMonth() + 1
      let date = new Date().getDate()
      let hours = new Date().getHours()
      let params = {
        'offset': 0,
        'limit': 2500,
        'date': {
          'begin': new Date(new Date(`${year}/${month}/${date}`) - number * 1000 * 60 * 60 * 24 + hours * 1000 * 60 * 60),
          'end': new Date(+new Date(`${year}/${month}/${date}`) + hours * 1000 * 60 * 60)
        }
      }
      return params
    },
    async fetchSnapshot (bottomFloor) {
      let productId = this.$route.params.product_id
      let deviceId = this.$route.params.device_id
      let params = this.getParams(this.date)
      let {data: { count, list }} = await api.fetchSnapshot(productId, deviceId, params)
      this.total = count
      this.snapshots = list.sort((a, b) => {
        return new Date(b.snapshot_date) - new Date(a.snapshot_date)
      })
      let { data } = await api.getDatapoints(this.$route.params.product_id)
      this.allDatapoints = data
    },
    async fetchDatapoint () {
      let { data } = await api.getDatapoints(this.$route.params.product_id)
      this.allDatapoints = data
    },
    // 1: 主控界面直接进入，获取所有连接实例
    // 2: 从localStorage获取当前设备（主控界面进入曲线图那一刻的当前设备，避免在曲线图刷新当前设备不一致）
    // 3: 如果当前连接实例为空 返回
    // 4: 有实例连接，为localStorage获取当前设备的为空则默认值为第一个，否则取对应的
    // 5: 获取连接实例是跨页面异步操作，watch连接实例
    linkSocket () {
      let socketlist = this.$store.getters['control/socketList']
      let currentDeviceId = window.localStorage.getItem('currentDeviceId')
      let currentDevice = null
      if (!socketlist.length) return
      if (!currentDeviceId) {
        currentDevice = socketlist[0]
      } else {
        currentDevice = _.filter(socketlist, (socket) => {
          return currentDeviceId === socket.id
        })[0]
      }
      // 存储currentDevice，为了曲线图刷新后返回控制界面对应相应的当前设备
      this.$store.dispatch('control/currentSocket', currentDevice)
      currentDevice.on('data', (data) => {
      // 后台改变的和当前设备不一致的时候不更新数据(后台多台设备，改变的不一定是当前显示的设备)
        if (data.type === 'datapoint') {
          // 数据端点
          let newDatas = data.data
          _.forEach(newDatas, (newData) => {
            _.forEach(this.allType, (oldData) => {
              if (oldData.key === newData.index) {
                oldData.value = newData.value
              }
            })
            if (newDatas.index === 2) {
              this.tempType = newDatas.value
            }
          })
        }
      })
    // 获取后台的数据端点
      currentDevice.emit('probe', (devices) => {
        if (devices.status === 0) {
          // 转化allType数据格式进行遍历
          devices.data.forEach(devices => {
            this.tempAndHum.forEach(item => {
              if (item.key === devices.index) {
                item.value = devices.value
              }
            })
            if (devices.index === 2) {
              this.tempType = devices.value
            }
          })
        }
      })
    },

    // 存储uiDevice和uiDeviceList，为了曲线图刷新后返回控制界面对应相应的当前设备
    storage () {
      let uiDeviceList = []
      if (this.getNameDevicesList && this.getNameDevicesList.length !== 0) {
        this.getNameDevicesList.forEach((item) => {
          let name = item.device_name ? item.device_name : item.device_mac
          uiDeviceList.push({
            name: name,
            id: item.device_id
          })
        })
        let currentDeviceId = window.localStorage.getItem('currentDeviceId')
        let uiDevice = uiDeviceList.filter(item => {
          return item.id === currentDeviceId
        })[0]

        this.$store.dispatch('control/uiDeviceList', uiDeviceList)
        this.$store.dispatch('control/uiDevice', uiDevice)
      }
    },
    canBeCounted (type) {
      return (type >= 2 && type <= 5) || type === 8 || type === 9 // 可统计的数据端点类型
    },
    changeOptions (orientation) {
      this.chartWidth = `${this.$refs.chartWrap.clientWidth}px`
      this.chartHeight = `${this.$refs.chartWrap.clientHeight}px`
      let {temArry, humArry} = this.series
      let rangeDate = this.date
      this.myChart.setOption({
        animation: false,
        boundaryGap: [0, '100%'],
        title: {
          left: 'center',
          text: 'Echarts'
        },
        tooltip: {
          trigger: 'axis',
          position: function (point, params, dom, rect, size) {
              // 固定是以鼠标为对象的
            return [point[0], point[1]]
          }
        },
        legend: {
          orient: 'vertical',
          data: [{
            name: '温度',
            textStyle: {fontWeight: 'bolder', color: 'rgb(244, 188, 133)', fontSize: 12}
          }, {
            name: '湿度',
            textStyle: {fontWeight: 'bolder', color: 'rgb(108, 177, 252)', fontSize: 12}
          }],
          right: '10px',
          icon: 'emptyCircle',
          top: '18px',
          itemGap: 6,
          itemWidth: 6,
          itemHeight: 6
        },
        grid: {
          left: '60px',
          right: '60px',
          bottom: '40px',
          top: '85px'
        },
        xAxis: {
          data: this.xAxisData,
          axisLine: {
            show: false,
            lineStyle: {
              color: '#5d5e64',
              width: 10
            }
          },
          axisTick: {
            show: false
          },
          boundaryGap: false,
          nameLocation: 'start',
          inverse: true,
          axisLabel: {
            formatter: function (value) {
              return rangeDate === 1 ? value.split(' ')[1] : value.split(' ')[0]
            }
          }
        },
        yAxis: [{
          // name: '温度',
          // min: 0,
          max: 60,
          type: 'value',
          position: 'left',
          axisLabel: {
            formatter: '{value}℃ '
          },
          splitLine: {
            show: true
          },
          axisLine: {
            show: false,
            lineStyle: {
              color: '#5d5e64',
              width: 10
            }
          },
          axisTick: {
            show: false
          }
        }, {
          // name: '湿度',
          min: 0,
          max: 100,
          type: 'value',
          position: 'right',
          axisLabel: {
            formatter: ' {value}%'
          },
          splitLine: {
            show: false
          },
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          }
        }],
        series: [{
          name: '温度',
          type: 'line',
          smooth: true,
          itemStyle: {
            normal: {
              color: 'rgb(244, 188, 133)'
            }
          },
          areaStyle: {
            normal: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgba(244, 188, 133, 1)' // 0% 处的颜色
                }, {
                  offset: 1, color: 'rgba(244, 188, 133, 0.1)'
                }],
                globalCoord: false // 缺省为 false
              }
            }
          },
          yAxisIndex: 0,
          data: temArry
        }, {
          name: '湿度',
          type: 'line',
          smooth: true,
          itemStyle: {
            normal: {
              color: 'rgb(108, 177, 252)'
            }
          },
          areaStyle: {
            normal: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                  offset: 0, color: 'rgba(149, 196, 248, 1)' // 0% 处的颜色
                }, {
                  offset: 1, color: 'rgba(149, 196, 248, 0.1)'
                }],
                globalCoord: false // 缺省为 false
              }
            }
          },
          yAxisIndex: 1,
          data: humArry
        }]
      })
      setTimeout(() => {
        this.myChart.resize()
      }, 100)
    },
    checkOrientation () {
      // 复制对象
      let _self = this
      window.addEventListener('onorientationchange' in window ? 'orientationchange' : 'resize', function () {
        if (window.orientation === 180 || window.orientation === 0) {
          window.clearTimeout(this.onorientationchangeId)
          this.onorientationchangeId = setTimeout(() => {
            _self.headerContent = '42.8%'
            _self.dateWidth = '84%'
            _self.headerLeftShow = true
            _self.changeOptions()
          }, 500)
        }
        if (window.orientation === 90 || window.orientation === -90) {
          window.clearTimeout(this.onorientationchangeId)
          this.onorientationchangeId = setTimeout(() => {
            _self.headerContent = '24.1%'
            _self.dateWidth = '46%'
            _self.headerLeftShow = false
            _self.changeOptions()
          }, 500)
        }
      }, false)
    }
  }
}
</script>
<style lang="stylus">
  .curve {
    height: 100%;
    display: flex;
    flex-direction: column;
    .header {
      height: 100px;
      padding: 21px 10px 36px 10px;
      box-sizing: border-box;
      display: flex;
      &__left {
        width: 100px;
      }
      &__content {
        flex: 1;
        .floor__wrap {
          color: #d1903e;
          border: 1px solid #d1903e;
          border-radius: 30px;
          text-align: center;
          display: flex;
          height: 100%;
          line-height: 30px;
          .top-floor, .bottom-floor {
            &.active {
              color: #fff;
              background-color: #d1903e;
            }
            height: 100%;
            border-bottom-left-radius: 30px;
            border-top-left-radius: 30px;
            flex: 1;
          }
          .bottom-floor.active {
            color: #fff;
            border-bottom-left-radius: 0px;
            border-top-left-radius: 0px;
            border-bottom-right-radius: 30px;
            border-top-right-radius: 30px;
          }
        }
      }
      &__right {
        text-align:right;
        width: 80px;
      }
    }
    .curve--chart__wrap {
      // margin-top: -44px;
      // position: absolute;
      flex: 1;
    }
    .footer {
      height: 50px;
      display: flex;
      justify-content: space-around;
      align-items: center;
      // padding-bottom: 60px;
      .date {
        &.active {
          background-color: #d1903e;
          color: #fff;
        }
        // color: #d1903e;
        color: rgb(147, 147, 147);
        background: rgb(227, 227, 227);
        box-sizing: border-box;
        border-radius: 20px;
        // border: 1px solid #d1903e;
        width: 60px;
        line-height: 30px;
        text-align: center;
        // height: 30px;
      }
    }
  }  
</style>
